import { message } from "ant-design-vue";
import axios from "axios";
import router from "../router/index-new";

// const axiosInstance = axios.create({
//   baseURL: "http://study.zmyfrank.com",
//   timeout: 10000,
// });
// const router = useRouter();
const axiosInstance = axios.create({
  baseURL: "/api",
  timeout: 10000,
});
axiosInstance.interceptors.request.use((requestObj) => {
  requestObj.headers.Authorization = localStorage.token;
  return requestObj;
});
//1. 通用的错误拦截
//2. 通用的正确拦截
//3. 处理后端错误
axiosInstance.interceptors.response.use(
  (responseObj) => {
    // console.log(responseObj);

    if (responseObj.data.code !== 0) {
      // 通用失败处理
      // if (responseObj.data.code === 110) {
      // }
      const errorMessage = responseObj.data.message || "后台错误，请联系管理员";
      message.error(errorMessage);
      throw errorMessage;
    } else {
      // 通用成功
      return responseObj.data.data;
    }
    // requestObj.headers.Authorization = localStorage.token;
    // return requestObj;
  },
  (errorObj) => {
    // console.log(errorObj);
    // switch (errorObj.response.status) {
    //   case 401:

    //     break;
    //     case 404:

    //     break;

    //   default:
    //     break;
    // }
    if (errorObj.response.status === 401) {
      debugger;
      localStorage.clear();
      router.push("/login");
      message.error("请重新登录！");
      throw "未登录";
    } else {
      message.error("后台错误，请联系管理员！");
      throw "后台错误，请联系管理员！";
    }
  }
);
export default axiosInstance;
